<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SmsService
{
    const apiurl='https://api.4321.sh/sms/template';
    const apikey='N40598da7a';
	const secret='405983792e93e62d';
    /**
     * 发送短信并限制60秒一次
     *
     * @param string $mobile 手机号
     * @param string $content 短信内容（需包含签名）
     * @return array 结果数组
     */
    public function sendWithLimit(string $mobile, string $content): array
    {
        // 1. 检查频率限制（60秒内只能发送一次）
        $cacheKey = "sms_limit:{$mobile}";
        if (Cache::has($cacheKey)) {
            return [
                'success' => false,
                'message' => '发送频率过高，请60秒后再试'
            ];
        }

        // 2. 发送短信
        $result = $this->sendSms($mobile, $content);

        // 3. 发送成功则设置缓存限制
        if ($result['success']) {
            Cache::put($cacheKey, true, 60); // 缓存60秒
        }

        return $result;
    }

    /**
     * 调用飞鸽平台API发送短信
     *
     * @param string $mobile 手机号
     * @param string $content 短信内容
     * @return array 接口返回结果
     */
    private function sendSms(string $mobile, string $content): array
    {
        try {
            $config = config('services.feige');

            // 飞鸽平台API参数（具体参数请参考官方文档）
            $params = [
                'apikey'  =>  self::apikey,
                'secret' => self::secret,
                'content' => $content,
                'mobile' => $mobile,
                'sign_id' => 121522,
                'template_id' => 121214
            ];

            // 调用飞鸽API
            $response = Http::timeout(60)
                ->post(self::apiurl, $params);

            $responseData = $response->json() ?? $response->body();


            // 记录短信发送日志
            Log::channel('sms')->info('飞鸽短信发送', [
                'mobile' => $mobile,
                'content' => $content,
                'response' => $responseData
            ]);

            // 根据飞鸽平台返回格式判断是否成功
            // 注意：不同平台返回格式不同，需根据实际文档调整
            if (isset($responseData['code']) && $responseData['code'] === 0) {
                return [
                    'success' => true,
                    'message' => '短信发送成功',
                    'data' => $responseData
                ];
            }

            return [
                'success' => false,
                'message' => $responseData['Message'] ?? '短信发送失败',
                'data' => $responseData
            ];

        } catch (\Exception $e) {
            Log::channel('sms')->error('飞鸽短信发送异常', [
                'mobile' => $mobile,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return [
                'success' => false,
                'message' => '发送请求失败，请稍后重试'
            ];
        }
    }
}
